package com.elinkway.infinitemovies.utils;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.apkfuns.logutils.LogUtils;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.AppListDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by richard on 2017/7/11.
 */
public class AppListUtil {

    public static final int DAY  = 86400000;
    public static final String ACODE = "101";

    public static void uploadAppList() {
        long lastUploadAppListTime = PreferencesManager.getInstance().getLastUpdateAppListTime();
        boolean isToday = isToday(lastUploadAppListTime);
        LogUtils.d("upload app list is today:" + isToday);
        if (!isToday) {
            AppListDataRecord appListDataRecord = MyDataRecordCreater.build(AppListDataRecord.class);
            if (appListDataRecord != null) {
                appListDataRecord.setAcode(ACODE);
                appListDataRecord.setThirdapp(getAppsPackageName());
                PreferencesManager.getInstance().setLastUpdateAppListTime(System.currentTimeMillis());
                RealmDaoManager.addMyDataRecord(appListDataRecord);
            }
        }
    }

    public static ArrayList<String> getAppsPackageName() {
        ArrayList<String> list = new ArrayList<>();
        PackageManager pm = MoviesApplication.getInstance().getPackageManager();
        List<PackageInfo> installedPackages = pm.getInstalledPackages(0);
        for (PackageInfo pi : installedPackages) {
            if (!isSystemApp(pi.packageName)) {
                list.add(pi.packageName);
            }
        }
        return list;
    }

    public static boolean isSystemApp(final String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        try {
            PackageManager pm = MoviesApplication.getInstance().getPackageManager();
            ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
            return ai != null && (ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean isToday(final long millis) {
        long wee = getWeeOfToday();
        return millis >= wee && millis < wee + DAY;
    }

    private static long getWeeOfToday() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis();
    }
}
